package com.team8.user.pojo.service;

import com.team8.common.results.Result;
import com.team8.system.pojo.FlightInfo;
import com.team8.system.pojo.FlightSegs;
import com.team8.user.pojo.dao.BookingDao;
import com.team8.user.pojo.dao.BookingHelpDao;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Iterator;
import java.util.List;

@Service
public class BookingService {

    @Autowired
    private BookingDao bookingDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BookingHelpDao bookingHelpDao;

    public Result booking(String ffid, String email, Integer startSeg, Integer endSeg) {

        String s = redisTemplate.opsForValue().get(ffid + ":max");
        if(StringUtils.isBlank(s)){
            putDataFromDBToRedis(ffid);
        }
        String key = ffid + ":" + startSeg + ":" + endSeg;
        Integer left = Integer.valueOf((redisTemplate.opsForValue().get(key)));

        if(left > 0){
            int max = Integer.valueOf(redisTemplate.opsForValue().get(ffid + ":max"));
            Long result = 0L;
            // i 是终点
            for(int i = startSeg + 1; i <= max; i++){
                // j 是起点，
                for(int j = 0; j < i && j < endSeg; j++){
                    String tempKey = ffid + ":" + j + ":" + i;
                    // 票数减一
                    result = redisTemplate.opsForValue().increment(tempKey, -1);
                    // 发送给数据库交换机
                    amqpTemplate.convertAndSend("as.refreshdb.exchange", "db.flightinfo.update", tempKey+":"+result);

                    // 发送给搜索交换机
                    amqpTemplate.convertAndSend("as.es.exchange", "es.flightinfo.update", tempKey+":"+result);
                }
            }

            // 订票的消息队列，发送ffid : startseg : endseg : emails
            amqpTemplate.convertAndSend("as.refreshdb.exchange", "db.ticketrecord.booking", key + ":" + email);

            return Result.getSuccessInstance();
        }

        return Result.getErrorInstance();
    }

    private void putDataFromDBToRedis(String ffid){
        Example example = new Example(FlightInfo.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("ffid", ffid);
        List<FlightInfo> flightInfos = bookingDao.selectByExample(example);
        Iterator<FlightInfo> iterator = flightInfos.iterator();
        while(iterator.hasNext()){
            FlightInfo next = iterator.next();
            // 把每个段的票数放在redis中
            redisTemplate.opsForValue().set(next.getFfid() + ":" + next.getStartSeg() + ":" + next.getEndSeg(), String.valueOf(next.getTicketNum()));
        }

        // 将此航班的最大段号设置在redis中  同时作为版本号，控制该航班信息再redis中是否存在
        Example example1 = new Example(FlightSegs.class);

        Example.Criteria criteria1 = example1.createCriteria();
        criteria1.andEqualTo("ffid", ffid);

        List<FlightSegs> flightSegs = bookingHelpDao.selectByExample(example1);

        if(!CollectionUtils.isEmpty(flightSegs)){

            FlightSegs flightSegs1 = flightSegs.get(0);
            redisTemplate.opsForValue().set(ffid+":max", String.valueOf(flightSegs1.getMax()));

        } else
            redisTemplate.opsForValue().set(ffid+":max", "0");

    }
}
